import React, { Component } from "react";
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  DeviceEventEmitter,
  Platform
} from "react-native";
import http from "../../util/http";
import { MESSAGE_UNREAD } from "../../config/Api";

export default class NavBarRightButton extends Component {
  state = {
    count: 0
  };

  async getUnreadMsg() {
    const data = await http.get(MESSAGE_UNREAD);

    this.setState({
      count: data.data
    });
  }

  refresh() {
    this.getUnreadMsg();
  }

  componentWillUnmount() {
    this.subscription.remove();
  }

  componentWillMount() {
    this.refresh();
    this.subscription = DeviceEventEmitter.addListener("refresh", () => {
      this.refresh();
    });
  }

  render() {
    const { navigate, isSetNotShow } = this.props;

    return (
      <View
        style={{
          // backgroundColor: "red",
          flexDirection: "row",
          alignItems: "center",
          width: isSetNotShow ? 40:75,
          right: 0,
          bottom: 5,
          paddingTop: 15
        }}
      >
        <TouchableOpacity onPress={() => navigate("MessageList")} style={{}}>
          <View style={{ flex: 1, position: "relative", paddingRight: 10 }}>
            {this.state.count > 0 ? (
              <Text
                style={{
                  position: "absolute",
                  right: 0,
                  top: 0,
                  zIndex: 9,
                  fontSize: 11,
                  width: Platform.OS == "ios" ? 15 : 18,
                  height: Platform.OS == "ios" ? 15 : 18,
                  backgroundColor: "red",
                  color: "white",
                  textAlign: "center",
                  lineHeight: Platform.OS == "ios" ? 15 : 18,
                  borderRadius: Platform.OS == "ios" ? 7.5 : 9,
                  overflow: "hidden"
                }}
              >
                {this.state.count}
              </Text>
            ) : null}
            <Image
              style={{
                resizeMode: "contain",
                width: 25,
                height: 25,
                bottom: -4
              }}
              source={require("../../assets/message-icon.png")}
            />
          </View>
        </TouchableOpacity>
        {isSetNotShow ? null : (
          <TouchableOpacity onPress={() => navigate("Setting")}>
            <View style={{ flex: 1, position: "relative" }}>
              <Image
                style={{
                  resizeMode: "contain",
                  width: 25
                }}
                source={require("../../assets/setting-icon.png")}
              />
            </View>
          </TouchableOpacity>
        )}
      </View>
    );
  }
}
